<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>相机测试系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    
    <!-- HarmonyOS 优化配置 -->
    <meta name="theme-color" content="#3880ff" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f8f9fa;
            height: 100vh;
            overflow: hidden;
        }
        
        .app-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: #3880ff;
            color: white;
            padding: 12px 16px;
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: relative;
        }
        
        .back-button {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 20px;
            cursor: pointer;
            padding: 4px;
        }
        
        .content {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }
        
        .debug-panel {
            background: #2d3748;
            color: #e2e8f0;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 120px;
            overflow-y: auto;
        }
        
        .status-card {
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .status-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 12px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .status-item:last-child {
            border-bottom: none;
        }
        
        .status-label {
            font-size: 14px;
            color: #666;
        }
        
        .status-value {
            font-size: 14px;
            font-weight: 500;
            padding: 4px 8px;
            border-radius: 4px;
        }
        
        .status-supported {
            background: #d4edda;
            color: #155724;
        }
        
        .status-unsupported {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-unknown {
            background: #fff3cd;
            color: #856404;
        }
        
        .button-group {
            display: grid;
            grid-template-columns: 1fr;
            gap: 12px;
            margin-bottom: 16px;
        }
        
        .test-button {
            background: #3880ff;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 16px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .test-button:hover {
            background: #3171e0;
            transform: translateY(-1px);
        }
        
        .test-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
        }
        
        .test-button.secondary {
            background: #6c757d;
        }
        
        .test-button.secondary:hover {
            background: #5a6268;
        }
        
        .test-button.success {
            background: #28a745;
        }
        
        .test-button.success:hover {
            background: #218838;
        }
        
        .test-button.system-camera {
            background: #ff6b35;
        }
        
        .test-button.system-camera:hover {
            background: #e55a2b;
        }
        
        .test-button.system-camera {
            background: #ff6b35;
            background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
        }
        
        .test-button.system-camera:hover {
            background: #e55a2b;
            background: linear-gradient(135deg, #e55a2b 0%, #e8851a 100%);
        }
        
        .photo-preview {
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .photo-container {
            width: 100%;
            max-width: 300px;
            margin: 0 auto;
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 20px;
            background: #f8f9fa;
        }
        
        .photo-placeholder {
            color: #666;
            font-size: 14px;
        }
        
        .photo-image {
            max-width: 100%;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .photo-info {
            margin-top: 12px;
            font-size: 12px;
            color: #666;
            text-align: left;
        }
        
        .device-list {
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .device-item {
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
        }
        
        .device-item:last-child {
            border-bottom: none;
        }
        
        .device-label {
            font-weight: 500;
            color: #333;
        }
        
        .device-id {
            color: #666;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            border: 1px solid #f5c6cb;
        }
        
        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            border: 1px solid #c3e6cb;
        }
        
        .platform-info {
            background: #e3f2fd;
            color: #0d47a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 16px;
            border: 1px solid #bbdefb;
        }
        
        .hidden {
            display: none !important;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <button class="back-button" onclick="goBack()">←</button>
            <span id="header-title">相机测试系统</span>
        </div>
        
        <div class="content">
            <!-- 调试面板 -->
            <div class="debug-panel" id="debug-panel">
                <div id="debug-log">正在初始化相机测试系统...</div>
            </div>
            
            <!-- 平台信息 -->
            <div class="platform-info" id="platform-info">
                <strong>平台信息：</strong><span id="platform-text">检测中...</span>
            </div>
            
            <!-- 相机状态卡片 -->
            <div class="status-card">
                <div class="status-title">
                    📷 相机支持状态
                </div>
                <div class="status-item">
                    <span class="status-label">HarmonyOS 原生相机</span>
                    <span class="status-value status-unknown" id="harmony-status">检测中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">Capacitor 相机插件</span>
                    <span class="status-value status-unknown" id="capacitor-status">检测中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">Web Camera API</span>
                    <span class="status-value status-unknown" id="webcam-status">检测中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">文件系统支持</span>
                    <span class="status-value status-unknown" id="filesystem-status">检测中...</span>
                </div>
            </div>
            
            <!-- 设备列表 -->
            <div class="device-list" id="device-list">
                <div class="status-title">
                    📱 可用设备
                </div>
                <div id="device-items">
                    <div class="device-item">正在检测设备...</div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="button-group">
                <button class="test-button" id="permission-btn" onclick="checkPermissions()">
                    <span id="permission-icon">🔐</span>
                    <span id="permission-text">检查相机权限</span>
                </button>
                
                <button class="test-button success" id="system-camera-btn" onclick="openSystemCamera()" style="background: #ff6b35;">
                    <span>📱</span>
                    <span>打开系统相机</span>
                </button>
                
                <button class="test-button success" id="photo-btn" onclick="takePhoto()" disabled>
                    <span>📸</span>
                    <span>拍摄照片 (Web API)</span>
                </button>
                
                <button class="test-button secondary" onclick="refreshStatus()">
                    <span>🔄</span>
                    <span>刷新状态</span>
                </button>
            </div>
            
            <!-- 照片预览 -->
            <div class="photo-preview">
                <div class="status-title">
                    🖼️ 照片预览
                </div>
                <div class="photo-container" id="photo-container">
                    <div class="photo-placeholder">暂无照片</div>
                </div>
                <div class="photo-info" id="photo-info"></div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let debugLog = [];
        let currentPhotoData = null;
        let availableDevices = [];
        
        // 调试日志函数
        function addLog(message) {
            const timestamp = new Date().toLocaleTimeString();
            const logMessage = `[${timestamp}] ${message}`;
            debugLog.push(logMessage);
            
            // 保持最新的20条日志
            if (debugLog.length > 20) {
                debugLog.shift();
            }
            
            const debugElement = document.getElementById('debug-log');
            if (debugElement) {
                debugElement.innerHTML = debugLog.join('<br>');
                debugElement.scrollTop = debugElement.scrollHeight;
            }
            
            console.log(logMessage);
        }
        
        // 更新状态显示
        function updateStatus(elementId, status, text) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = text;
                element.className = 'status-value';
                
                if (status === 'supported') {
                    element.classList.add('status-supported');
                } else if (status === 'unsupported') {
                    element.classList.add('status-unsupported');
                } else {
                    element.classList.add('status-unknown');
                }
            }
        }
        
        // 显示错误消息
        function showError(message) {
            addLog(`错误: ${message}`);
            
            // 移除现有的错误消息
            const existingError = document.querySelector('.error-message');
            if (existingError) {
                existingError.remove();
            }
            
            // 创建新的错误消息
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            
            // 插入到内容区域顶部
            const content = document.querySelector('.content');
            content.insertBefore(errorDiv, content.firstChild);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (errorDiv.parentNode) {
                    errorDiv.remove();
                }
            }, 3000);
        }
        
        // 显示成功消息
        function showSuccess(message) {
            addLog(`成功: ${message}`);
            
            // 移除现有的成功消息
            const existingSuccess = document.querySelector('.success-message');
            if (existingSuccess) {
                existingSuccess.remove();
            }
            
            // 创建新的成功消息
            const successDiv = document.createElement('div');
            successDiv.className = 'success-message';
            successDiv.textContent = message;
            
            // 插入到内容区域顶部
            const content = document.querySelector('.content');
            content.insertBefore(successDiv, content.firstChild);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (successDiv.parentNode) {
                    successDiv.remove();
                }
            }, 3000);
        }
        
        // 检测平台
        async function detectPlatform() {
            addLog('开始检测平台信息...');
            
            let platform = '未知平台';
            const userAgent = navigator.userAgent;
            
            if (userAgent.includes('HarmonyOS')) {
                platform = 'HarmonyOS';
            } else if (/Android/i.test(userAgent)) {
                platform = 'Android';
            } else if (/iPhone|iPad|iPod/i.test(userAgent)) {
                platform = 'iOS';
            } else if (/Windows/i.test(userAgent)) {
                platform = 'Windows';
            } else if (/Mac/i.test(userAgent)) {
                platform = 'macOS';
            } else if (/Linux/i.test(userAgent)) {
                platform = 'Linux';
            }
            
            const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
            const platformText = `${platform} ${isMobile ? '(移动设备)' : '(桌面设备)'}`;
            
            document.getElementById('platform-text').textContent = platformText;
            addLog(`平台检测完成: ${platformText}`);
            
            return { platform, isMobile, userAgent };
        }
        
        // 检测相机状态
        async function detectCameraStatus() {
            addLog('开始检测相机支持状态...');
            
            try {
                // 检测 HarmonyOS 原生相机
                if (window.harmony && window.harmony.camera && typeof window.harmony.camera.isAvailable === 'function') {
                    try {
                        const isAvailable = window.harmony.camera.isAvailable();
                        if (isAvailable) {
                            updateStatus('harmony-status', 'supported', '支持');
                            addLog('HarmonyOS 原生相机: 支持');
                            
                            // 启用系统相机按钮
                            const systemCameraBtn = document.getElementById('system-camera-btn');
                            if (systemCameraBtn) {
                                systemCameraBtn.disabled = false;
                            }
                        } else {
                            updateStatus('harmony-status', 'unsupported', '不可用');
                            addLog('HarmonyOS 原生相机: 不可用');
                        }
                    } catch (error) {
                        updateStatus('harmony-status', 'unsupported', '检测失败');
                        addLog(`HarmonyOS 相机检测失败: ${error.message}`);
                    }
                } else {
                    updateStatus('harmony-status', 'unsupported', '不支持');
                    addLog('HarmonyOS 原生相机: 不支持');
                }
                
                // 检测 Capacitor 相机
                if (window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Camera) {
                    updateStatus('capacitor-status', 'supported', '支持');
                    addLog('Capacitor 相机插件: 支持');
                } else {
                    updateStatus('capacitor-status', 'unsupported', '不支持');
                    addLog('Capacitor 相机插件: 不支持');
                }
                
                // 检测 Web Camera API
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    updateStatus('webcam-status', 'supported', '支持');
                    addLog('Web Camera API: 支持');
                    
                    // 枚举设备
                    await enumerateDevices();
                } else {
                    updateStatus('webcam-status', 'unsupported', '不支持');
                    addLog('Web Camera API: 不支持');
                }
                
                // 检测文件系统支持
                if (window.File && window.FileReader && window.FileList && window.Blob) {
                    updateStatus('filesystem-status', 'supported', '支持');
                    addLog('文件系统 API: 支持');
                } else {
                    updateStatus('filesystem-status', 'unsupported', '不支持');
                    addLog('文件系统 API: 不支持');
                }
                
            } catch (error) {
                addLog(`相机状态检测出错: ${error.message}`);
                showError(`相机状态检测失败: ${error.message}`);
            }
        }
        
        // 枚举设备
        async function enumerateDevices() {
            try {
                const devices = await navigator.mediaDevices.enumerateDevices();
                const videoDevices = devices.filter(device => device.kind === 'videoinput');
                
                availableDevices = videoDevices;
                
                const deviceContainer = document.getElementById('device-items');
                if (videoDevices.length > 0) {
                    deviceContainer.innerHTML = '';
                    videoDevices.forEach((device, index) => {
                        const deviceDiv = document.createElement('div');
                        deviceDiv.className = 'device-item';
                        deviceDiv.innerHTML = `
                            <div class="device-label">${device.label || `相机 ${index + 1}`}</div>
                            <div class="device-id">${device.deviceId}</div>
                        `;
                        deviceContainer.appendChild(deviceDiv);
                    });
                    addLog(`发现 ${videoDevices.length} 个视频设备`);
                } else {
                    deviceContainer.innerHTML = '<div class="device-item">未发现视频设备</div>';
                    addLog('未发现任何视频设备');
                }
            } catch (error) {
                addLog(`设备枚举失败: ${error.message}`);
                document.getElementById('device-items').innerHTML = '<div class="device-item">设备枚举失败</div>';
            }
        }
        
        // 检查权限
        async function checkPermissions() {
            console.log('🔍 checkPermissions 函数被调用');
            addLog('🔍 checkPermissions 函数开始执行');
            
            // 触发HarmonyOS原生权限检查
            console.log('🔍 准备触发HarmonyOS原生权限检查');
            addLog('🔍 准备触发HarmonyOS原生权限检查');
            
            // 检查HarmonyOS原生接口是否可用
            if (window.harmony && window.harmony.camera && typeof window.harmony.camera.requestPermission === 'function') {
                console.log('🔍 HarmonyOS相机接口可用，请求权限');
                addLog('🔍 HarmonyOS相机接口可用，请求权限');
                try {
                    const permissionResult = await window.harmony.camera.requestPermission();
                    console.log('🔍 HarmonyOS权限请求结果:', permissionResult);
                    addLog('🔍 HarmonyOS权限请求结果: ' + JSON.stringify(permissionResult));
                    
                    if (permissionResult && permissionResult.granted) {
                        showSuccess('HarmonyOS相机权限获取成功');
                        document.getElementById('photo-btn').disabled = false;
                        document.getElementById('system-camera-btn').disabled = false;
                        return;
                    }
                } catch (error) {
                    console.log('🔍 HarmonyOS权限请求失败:', error);
                    addLog('🔍 HarmonyOS权限请求失败: ' + error.message);
                }
            } else {
                console.log('🔍 HarmonyOS相机接口不可用');
                addLog('🔍 HarmonyOS相机接口不可用');
            }
            
            const btn = document.getElementById('permission-btn');
            const icon = document.getElementById('permission-icon');
            const text = document.getElementById('permission-text');
            
            console.log('🔍 获取到的DOM元素:', { btn, icon, text });
            
            // 禁用按钮并显示加载状态
            btn.disabled = true;
            icon.innerHTML = '<div class="loading-spinner"></div>';
            text.textContent = '检查中...';
            
            try {
                console.log('🔍 步骤1: 开始检查相机权限...');
                addLog('开始检查相机权限...');
                
                // 检查权限状态
                console.log('🔍 步骤2: 检查 navigator.permissions 是否可用');
                if (navigator.permissions) {
                    console.log('🔍 步骤2.1: navigator.permissions 可用，查询相机权限');
                    try {
                        const permission = await navigator.permissions.query({ name: 'camera' });
                        console.log('🔍 步骤2.2: 权限查询成功:', permission.state);
                        addLog(`权限状态: ${permission.state}`);
                    } catch (e) {
                        console.log('🔍 步骤2.3: 权限查询失败:', e);
                        addLog('无法查询权限状态');
                    }
                } else {
                    console.log('🔍 步骤2.4: navigator.permissions 不可用');
                }
                
                // 尝试获取相机流
                console.log('🔍 步骤3: 准备获取相机流');
                const constraints = {
                    video: {
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: 'environment'
                    }
                };
                console.log('🔍 步骤3.1: 相机约束设置:', constraints);
                
                console.log('🔍 步骤3.2: 调用 getUserMedia...');
                const stream = await navigator.mediaDevices.getUserMedia(constraints);
                console.log('🔍 步骤3.3: getUserMedia 成功，获得流:', stream);
                
                console.log('🔍 步骤4: 检查获得的流');
                if (stream) {
                    console.log('🔍 步骤4.1: 流存在，获取视频轨道');
                    const tracks = stream.getVideoTracks();
                    console.log('🔍 步骤4.2: 视频轨道数量:', tracks.length);
                    
                    if (tracks.length > 0) {
                        const track = tracks[0];
                        const settings = track.getSettings();
                        
                        console.log('🔍 步骤4.3: 轨道设置:', settings);
                        addLog(`相机权限获取成功`);
                        addLog(`分辨率: ${settings.width}x${settings.height}`);
                        addLog(`设备标签: ${track.label}`);
                        
                        console.log('🔍 步骤4.4: 显示成功消息');
                        showSuccess('相机权限检查通过，可以使用相机功能');
                        
                        // 启用拍照按钮
                        console.log('🔍 步骤4.5: 启用拍照按钮');
                        document.getElementById('photo-btn').disabled = false;
                        
                        // 停止流
                        console.log('🔍 步骤4.6: 停止相机流');
                        stream.getTracks().forEach(track => track.stop());
                    } else {
                        console.log('🔍 步骤4.7: 没有找到视频轨道');
                    }
                } else {
                    console.log('🔍 步骤4.8: 流为空');
                }
                
            } catch (error) {
                console.log('🔍 错误捕获: 权限检查失败:', error);
                addLog(`权限检查失败: ${error.message}`);
                
                let errorMessage = '相机权限检查失败';
                if (error.name === 'NotAllowedError') {
                    errorMessage = '用户拒绝了相机权限';
                } else if (error.name === 'NotFoundError') {
                    errorMessage = '未找到相机设备';
                } else if (error.name === 'NotSupportedError') {
                    errorMessage = '浏览器不支持相机功能';
                } else if (error.name === 'NotReadableError') {
                    errorMessage = '相机设备被其他应用占用';
                }
                
                showError(errorMessage);
            } finally {
                // 恢复按钮状态
                btn.disabled = false;
                icon.textContent = '🔐';
                text.textContent = '检查相机权限';
            }
        }
        
        // 打开系统相机
        async function openSystemCamera() {
            console.log('📱 openSystemCamera 函数被调用');
            addLog('📱 openSystemCamera 函数开始执行');
            
            // 触发HarmonyOS原生相机打开
            console.log('📱 准备触发HarmonyOS原生相机打开');
            addLog('📱 准备触发HarmonyOS原生相机打开');
            
            const btn = document.getElementById('system-camera-btn');
            const originalText = btn.innerHTML;
            
            console.log('📱 获取到的按钮元素:', btn);
            
            try {
                // 显示加载状态
                btn.disabled = true;
                btn.innerHTML = '<div class="loading-spinner"></div><span>正在打开相机...</span>';
                
                addLog('正在打开 HarmonyOS 系统相机...');
                
                // 检查 HarmonyOS 相机接口
                if (!window.harmony || !window.harmony.camera) {
                    throw new Error('HarmonyOS 相机接口不可用');
                }
                
                // 初始化相机
                addLog('初始化相机...');
                const initResult = await window.harmony.camera.initialize();
                if (!initResult) {
                    throw new Error('相机初始化失败');
                }
                
                addLog('相机初始化成功，正在拍摄...');
                
                // 拍摄照片
                const result = await window.harmony.camera.takePhoto({
                    quality: 80,
                    allowEdit: false,
                    source: 'camera'
                });
                
                if (result && result.success && result.data) {
                    addLog('系统相机拍摄成功');
                    displayPhoto(result.data);
                    showSuccess('系统相机拍摄成功！');
                } else {
                    throw new Error(result.error || '拍摄失败');
                }
                
            } catch (error) {
                addLog(`系统相机失败: ${error.message}`);
                showError(`系统相机失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                btn.disabled = false;
                btn.innerHTML = originalText;
                
                // 释放相机资源
                try {
                    if (window.harmony && window.harmony.camera && window.harmony.camera.release) {
                        await window.harmony.camera.release();
                        addLog('相机资源已释放');
                    }
                } catch (releaseError) {
                    addLog(`释放相机资源失败: ${releaseError.message}`);
                }
            }
        }
        
        // 拍摄照片
        async function takePhoto() {
            console.log('📸 takePhoto 函数被调用');
            addLog('📸 takePhoto 函数开始执行');
            
            // 触发HarmonyOS原生拍照
            console.log('📸 准备触发HarmonyOS原生拍照');
            addLog('📸 准备触发HarmonyOS原生拍照');
            
            addLog('开始拍摄照片...');
            
            try {
                let photoData = null;
                
                // 尝试使用 HarmonyOS 原生相机
                if (window.harmony && window.harmony.camera && typeof window.harmony.camera.takePhoto === 'function') {
                    addLog('使用 HarmonyOS 原生相机');
                    try {
                        // 检查相机是否可用
                        addLog('检查相机可用性...');
                        const isAvailable = window.harmony.camera.isAvailable();
                        addLog(`相机可用性: ${isAvailable}`);
                        
                        if (!isAvailable) {
                            addLog('相机不可用，尝试初始化...');
                        }
                        
                        // 先初始化相机
                        addLog('开始初始化相机...');
                        const initResult = await window.harmony.camera.initialize();
                        addLog(`相机初始化结果: ${initResult}`);
                        
                        if (initResult) {
                            addLog('相机初始化成功，开始拍照...');
                            const result = await window.harmony.camera.takePhoto({
                                quality: 80
                            });
                            
                            addLog(`拍照结果: ${JSON.stringify(result)}`);
                            
                            if (result && result.success && result.data) {
                                photoData = result.data;
                                addLog('HarmonyOS 相机拍摄成功');
                                addLog(`照片数据长度: ${result.data.length} 字符`);
                            } else {
                                addLog(`HarmonyOS 相机失败: ${result ? result.error : '结果为空'}`);
                            }
                        } else {
                            addLog('HarmonyOS 相机初始化失败');
                        }
                    } catch (error) {
                        addLog(`HarmonyOS 相机异常: ${error.message}`);
                        addLog(`错误堆栈: ${error.stack}`);
                    }
                } else {
                    addLog('HarmonyOS 相机接口不可用');
                    addLog(`window.harmony: ${!!window.harmony}`);
                    addLog(`window.harmony.camera: ${!!(window.harmony && window.harmony.camera)}`);
                    addLog(`takePhoto 方法: ${!!(window.harmony && window.harmony.camera && window.harmony.camera.takePhoto)}`);
                }
                
                // 尝试使用 Capacitor 相机
                if (!photoData && window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Camera) {
                    addLog('使用 Capacitor 相机插件');
                    try {
                        const Camera = window.Capacitor.Plugins.Camera;
                        const result = await Camera.getPhoto({
                            quality: 80,
                            allowEditing: false,
                            resultType: 'base64',
                            source: 'camera'
                        });
                        
                        if (result && result.base64String) {
                            photoData = result.base64String;
                            addLog('Capacitor 相机拍摄成功');
                        }
                    } catch (error) {
                        addLog(`Capacitor 相机失败: ${error.message}`);
                    }
                }
                
                // 尝试使用 Web Camera API
                if (!photoData && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    addLog('使用 Web Camera API');
                    try {
                        photoData = await captureWebPhoto();
                        if (photoData) {
                            addLog('Web Camera 拍摄成功');
                        }
                    } catch (error) {
                        addLog(`Web Camera 失败: ${error.message}`);
                    }
                }
                
                if (photoData) {
                    displayPhoto(photoData);
                    showSuccess('照片拍摄成功！');
                } else {
                    throw new Error('所有相机方法都失败了');
                }
                
            } catch (error) {
                addLog(`拍摄失败: ${error.message}`);
                showError(`拍摄失败: ${error.message}`);
            }
        }
        
        // Web Camera 拍摄
        async function captureWebPhoto() {
            return new Promise(async (resolve, reject) => {
                let stream = null;
                let video = null;
                
                try {
                    const constraints = {
                        video: {
                            width: { ideal: 1280 },
                            height: { ideal: 720 },
                            facingMode: 'environment'
                        }
                    };
                    
                    stream = await navigator.mediaDevices.getUserMedia(constraints);
                    
                    video = document.createElement('video');
                    video.srcObject = stream;
                    video.autoplay = true;
                    video.playsInline = true;
                    
                    // 等待视频加载
                    await new Promise((videoResolve, videoReject) => {
                        const timeout = setTimeout(() => {
                            videoReject(new Error('视频加载超时'));
                        }, 10000);
                        
                        video.onloadedmetadata = () => {
                            clearTimeout(timeout);
                            videoResolve();
                        };
                        
                        video.onerror = () => {
                            clearTimeout(timeout);
                            videoReject(new Error('视频加载失败'));
                        };
                    });
                    
                    // 创建画布并捕获图像
                    const canvas = document.createElement('canvas');
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(video, 0, 0);
                    
                    // 转换为 base64
                    const base64Data = canvas.toDataURL('image/jpeg', 0.8).split(',')[1];
                    resolve(base64Data);
                    
                } catch (error) {
                    reject(error);
                } finally {
                    // 清理资源
                    if (stream) {
                        stream.getTracks().forEach(track => track.stop());
                    }
                    if (video) {
                        video.srcObject = null;
                        video.remove();
                    }
                }
            });
        }
        
        // 显示照片
        function displayPhoto(base64Data) {
            currentPhotoData = base64Data;
            
            const container = document.getElementById('photo-container');
            const info = document.getElementById('photo-info');
            
            // 创建图片元素
            const img = document.createElement('img');
            img.src = `data:image/jpeg;base64,${base64Data}`;
            img.className = 'photo-image';
            img.alt = '拍摄的照片';
            
            // 清空容器并添加图片
            container.innerHTML = '';
            container.appendChild(img);
            
            // 显示照片信息
            const dataSize = Math.round((base64Data.length * 3) / 4 / 1024);
            const timestamp = new Date().toLocaleString();
            
            info.innerHTML = `
                <strong>拍摄时间:</strong> ${timestamp}<br>
                <strong>文件大小:</strong> 约 ${dataSize} KB<br>
                <strong>格式:</strong> JPEG<br>
                <strong>编码:</strong> Base64
            `;
            
            addLog(`照片显示成功，大小: ${dataSize} KB`);
        }
        
        // 刷新状态
        async function refreshStatus() {
            addLog('刷新状态...');
            
            // 重置状态
            updateStatus('harmony-status', 'unknown', '检测中...');
            updateStatus('capacitor-status', 'unknown', '检测中...');
            updateStatus('webcam-status', 'unknown', '检测中...');
            updateStatus('filesystem-status', 'unknown', '检测中...');
            
            document.getElementById('platform-text').textContent = '检测中...';
            document.getElementById('device-items').innerHTML = '<div class="device-item">正在检测设备...</div>';
            
            // 禁用拍照按钮
            document.getElementById('photo-btn').disabled = true;
            
            // 禁用系统相机按钮
            document.getElementById('system-camera-btn').disabled = true;
            
            // 重新检测
            await detectPlatform();
            await detectCameraStatus();
        }
        
        // 返回按钮
        function goBack() {
            addLog('返回主应用');
            if (window.history.length > 1) {
                window.history.back();
            } else {
                window.location.href = './index.html';
            }
        }
        
        // 初始化
        async function initCameraTest() {
            try {
                addLog('初始化相机测试系统...');
                
                await detectPlatform();
                await detectCameraStatus();
                
                addLog('相机测试系统初始化完成');
                
            } catch (error) {
                addLog(`初始化失败: ${error.message}`);
                showError(`初始化失败: ${error.message}`);
            }
        }
        
        // HarmonyOS回调函数
        window.onHarmonyOSPermissionResult = function(granted) {
            console.log('📱 收到HarmonyOS权限检查结果:', granted);
            addLog('📱 收到HarmonyOS权限检查结果: ' + (granted ? '已授权' : '未授权'));
            
            const btn = document.getElementById('permission-btn');
            const icon = document.getElementById('permission-icon');
            const text = document.getElementById('permission-text');
            
            if (granted) {
                icon.innerHTML = '✅';
                text.textContent = '权限已获取';
                btn.style.background = '#28a745';
                
                // 启用拍照按钮
                const photoBtn = document.getElementById('photo-btn');
                if (photoBtn) {
                    photoBtn.disabled = false;
                    photoBtn.style.background = '#007bff';
                }
            } else {
                icon.innerHTML = '❌';
                text.textContent = '权限被拒绝';
                btn.style.background = '#dc3545';
            }
            
            btn.disabled = false;
        };
        
        window.onHarmonyOSCameraOpened = function(success) {
            console.log('📱 收到HarmonyOS相机打开结果:', success);
            addLog('📱 收到HarmonyOS相机打开结果: ' + (success ? '成功' : '失败'));
        };
        
        window.onHarmonyOSPhotoTaken = function(photoData) {
            console.log('📱 收到HarmonyOS拍照结果:', photoData ? '成功' : '失败');
            addLog('📱 收到HarmonyOS拍照结果: ' + (photoData ? '成功' : '失败'));
            
            if (photoData) {
                // 显示拍摄的照片
                const photoContainer = document.getElementById('photo-container');
                if (photoContainer) {
                    photoContainer.innerHTML = `<img src="${photoData}" style="max-width: 100%; height: auto;" alt="拍摄的照片">`;
                }
            }
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('📄 页面DOM加载完成');
            addLog('📄 页面DOM加载完成');
            
            // 验证关键函数是否存在
            console.log('🔍 checkPermissions 函数存在:', typeof checkPermissions === 'function');
            console.log('🔍 openSystemCamera 函数存在:', typeof openSystemCamera === 'function');
            console.log('🔍 takePhoto 函数存在:', typeof takePhoto === 'function');
            
            // 验证HarmonyOS回调函数是否存在
            console.log('🔍 HarmonyOS回调函数已注册:', {
                onHarmonyOSPermissionResult: typeof window.onHarmonyOSPermissionResult === 'function',
                onHarmonyOSCameraOpened: typeof window.onHarmonyOSCameraOpened === 'function',
                onHarmonyOSPhotoTaken: typeof window.onHarmonyOSPhotoTaken === 'function'
            });
            
            initCameraTest();
        });
        
        // 全局错误处理
        window.addEventListener('error', function(e) {
            addLog(`脚本错误: ${e.message}`);
        });
        
        window.addEventListener('unhandledrejection', function(e) {
            addLog(`未处理的Promise错误: ${e.reason}`);
        });
        
        addLog('相机测试脚本加载完成');
    </script>
</body>
</html>